package cn.qingyun.gis.modules.init.utils;

import cn.hutool.core.util.ObjectUtil;
import cn.qingyun.gis.modules.express.entity.ExpressRegion;
import lombok.extern.slf4j.Slf4j;
import org.locationtech.jts.geom.Geometry;
import org.locationtech.jts.geom.GeometryFactory;
import org.locationtech.jts.geom.PrecisionModel;
import org.locationtech.jts.io.WKTReader;
import org.locationtech.jts.io.WKTWriter;

import java.util.List;

@Slf4j
public class JTSUtil {
    /**
     *   利用JTS库对业务区划中边界WKT数据进行精度降低
     *
     */

    public static void reduceAccuracy(List<ExpressRegion> regionDatas) {
        // 设置降低精度模型
        PrecisionModel precisionModel = new PrecisionModel(PrecisionModel.FLOATING_SINGLE);
        // 创建WKTReader对象
        WKTReader wktReader = new WKTReader(new GeometryFactory(precisionModel));
        // 创建WKTWriter对象
        WKTWriter wktWriter = new WKTWriter();
        try {
            for (ExpressRegion data : regionDatas) {
                if(ObjectUtil.isNotEmpty(data.getGeometry())){
                    // 解析WKT数据为Geometry对象
                    Geometry geometry = wktReader.read(data.getGeometry());
                    // 将Geometry对象转换为WKT数据
                    String convertedWKT = wktWriter.write(geometry);
                    data.setGeometry(convertedWKT);
                }
            }
        } catch (org.locationtech.jts.io.ParseException e) {
            log.error("边界数据降低精度失败");
        }

    }
}
